package com.himiotech.core.project.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.exception.HimioException;
import com.himiotech.core.project.data.mapper.PostMapper;
import com.himiotech.core.project.data.mapper.UserPostMapper;
import com.himiotech.core.project.model.entity.Post;
import com.himiotech.core.project.model.metadata.PostMetadata;
import com.himiotech.core.project.service.IPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 岗位信息 服务层处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserPostMapper userPostMapper;

    /**
     * 查询分页数据
     *
     * @param page 分页信息
     * @param post 业务信息查询条件
     * @return 分页对象及数据
     */
    @Override
    public Page<Post> selectPostListPage(Page<Post> page, Post post) {
        QueryWrapper<Post> query = Wrappers.query();
        query.like(ObjectUtil.isNotEmpty(post.getPostCode()), PostMetadata.POST_CODE.getColName(), post.getPostCode());
        query.like(ObjectUtil.isNotEmpty(post.getPostName()), PostMetadata.POST_NAME.getColName(), post.getPostName());
        query.eq(ObjectUtil.isNotEmpty(post.getStatus()), PostMetadata.STATUS.getColName(), post.getStatus());
        page = postMapper.selectPage(page, query);
        return page;
    }


    /**
     * 根据用户ID查询岗位
     *
     * @param userId 用户ID
     * @return 岗位列表
     */
    @Override
    public List<Post> selectPostsByUserId(Long userId) {
        List<Post> userPosts = postMapper.selectPostsByUserId(userId);
        List<Post> posts = this.list();
        for (Post post : posts) {
            for (Post userRole : userPosts) {
                if (post.getPostId().longValue() == userRole.getPostId().longValue()) {
                    post.setFlag(true);
                    post.setSelected(true);
                    break;
                }
            }
        }
        return posts;
    }

    /**
     * 批量删除岗位信息
     *
     * @param ids 需要删除的数据ID
     */
    @Override
    public int deletePostByIds(String ids) {
        Long[] postIds = Convert.toLongArray(ids.split(","));
        for (Long postId : postIds) {
            Post post = postMapper.selectById(postId);
            if (countUserPostById(postId) > 0) {
                throw new HimioException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        return postMapper.deleteBatchIds(Arrays.stream(postIds).collect(Collectors.toList()));
    }

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public int countUserPostById(Long postId) {
        return userPostMapper.countUserPostById(postId);
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostNameUnique(Post post) {
        long postId = post.getPostId() == null ? -1L : post.getPostId();
        Post info = postMapper.checkPostNameUnique(post.getPostName());
        if (info != null && info.getPostId() != postId) {
            return UserConstants.POST_NAME_NOT_UNIQUE;
        }
        return UserConstants.POST_NAME_UNIQUE;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostCodeUnique(Post post) {
        long postId = post.getPostId() == null ? -1L : post.getPostId();
        Post info = postMapper.checkPostCodeUnique(post.getPostCode());
        if (info != null && info.getPostId() != postId) {
            return UserConstants.POST_CODE_NOT_UNIQUE;
        }
        return UserConstants.POST_CODE_UNIQUE;
    }
}
